<template>
  <div class="app-container">

    <el-row :gutter="20" class="mb8">
      <el-col :span="6">
        <el-card shadow="hover">
          <div slot="header" class="clearfix">
            <span>盘盈商品种类数</span>
          </div>
          <div class="text-center">
            <h2 class="text-success">{{ profitLossStats.totalProfitCount }}</h2>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div slot="header" class="clearfix">
            <span>盘亏商品种类数</span>
          </div>
          <div class="text-center">
            <h2 class="text-danger">{{ profitLossStats.totalLossCount }}</h2>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <div slot="header" class="clearfix">
            <span>盘亏盘盈总金额</span>
          </div>
          <div class="text-center">
            <h2 :class="{'text-success': profitLossStats.totalProfitLossAmount > 0, 'text-danger': profitLossStats.totalProfitLossAmount < 0}">
              {{ formatAmount(profitLossStats.totalProfitLossAmount) }}
            </h2>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="盘点编号" prop="sn">
        <el-input
          v-model="queryParams.sn"
          placeholder="请输入库存盘点单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="未审核" value="未审核" />
          <el-option label="审核通过" value="审核通过" />
          <el-option label="审核驳回" value="审核驳回" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:inventory:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:inventory:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="inventoryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="库存盘点单编号" align="center" prop="sn" />
      <el-table-column label="盘点时间" align="center" prop="inventoryTime" />
      <el-table-column label="仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="盘点人" align="center" prop="inventoryPerson" />
      <el-table-column label="审核人" align="center" prop="auditPersonName" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '审核通过' ? 'success' : scope.row.status === '审核驳回' ? 'danger' : 'warning'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="盘盈种类数" align="center" prop="profitCount" width="100">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.profitCount > 0">{{ scope.row.profitCount }}</el-tag>
          <span v-else>0</span>
        </template>
      </el-table-column>
      <el-table-column label="盘亏种类数" align="center" prop="lossCount" width="100">
        <template slot-scope="scope">
          <el-tag type="danger" v-if="scope.row.lossCount > 0">{{ scope.row.lossCount }}</el-tag>
          <span v-else>0</span>
        </template>
      </el-table-column>
      <el-table-column label="盘亏盘盈金额" align="center" prop="profitLossAmount" width="120">
        <template slot-scope="scope">
          <span :class="{'text-success': scope.row.profitLossAmount > 0, 'text-danger': scope.row.profitLossAmount < 0}">
            {{ formatAmount(scope.row.profitLossAmount) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['system:inventory:query']"
          >详情</el-button>
          <el-button
            v-if="scope.row.status === '未审核'"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleAudit(scope.row)"
            v-hasPermi="['system:inventory:audit']"
          >审核</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:inventory:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改库存盘点单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <!-- 编号 -->
        <el-form-item label="编号" prop="sn">
          <el-input
            v-model="form.sn"
            placeholder="请输入编号"
            :disabled="form.isAdd"
            class="uniform-width"
          />
        </el-form-item>

        <!-- 部门名称 -->
        <el-form-item label="部门名称" prop="deptId">
          <el-select
            v-model="form.deptId"
            placeholder="请选择部门名称"
            clearable
            class="uniform-width"
          >
            <el-option
              v-for="dept in deptOptions"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>

        <!-- 仓库名称 -->
        <el-form-item label="仓库名称" prop="warehouseId">
          <el-select
            v-model="form.warehouseId"
            placeholder="请选择仓库名称"
            clearable
            class="uniform-width"
          >
            <el-option
              v-for="warehouse in warehouseOptions"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>

        <!-- 盘点人 -->
        <el-form-item label="盘点人">
          <el-cascader
            v-model="form.inventoryPersonId"
            :options="personList"
            :props="{ checkStrictly: true, value: 'id', label: 'realName' }"
            placeholder="请选择盘点人"
            class="uniform-width"
            @change="handleCreatorChange"
          />
        </el-form-item>

        <!-- 制单人 -->
        <el-form-item label="制单人">
          <el-cascader
            v-model="form.creatorId"
            :options="personList"
            :props="{ checkStrictly: true, value: 'id', label: 'realName' }"
            placeholder="请选择制单人"
            class="uniform-width"
            @change="handleCreatorChange2"
          />
        </el-form-item>

        <!-- 盘点时间 -->
        <el-form-item label="盘点时间" prop="inventoryTime">
          <el-date-picker
            v-model="form.inventoryTime"
            type="date"
            placeholder="选择盘点时间"
            value-format="yyyy-MM-dd"
            class="uniform-width"
          />
        </el-form-item>

        <!-- 盘点说明 -->
        <el-form-item label="盘点说明" prop="inventoryDesc">
          <el-input
            v-model="form.inventoryDesc"
            type="textarea"
            placeholder="请输入盘点说明"
            class="uniform-width"
          />
        </el-form-item>

        <!--商品明细-->
        <el-form-item label="商品明细">
          <el-button
            type="primary"
            size="mini"
            @click="handleSelectProducts"
            :disabled="!form.warehouseId">
            选择商品
          </el-button>

          <el-table
            :data="form.productList"
            border
            style="width: 100%; margin-top: 10px"
            v-if="form.productList && form.productList.length > 0">
            <el-table-column prop="goodsName" label="商品名称" width="180" align="center"></el-table-column>
            <el-table-column prop="goodsSn" label="商品编号" align="center"></el-table-column>
            <el-table-column prop="specification" label="规格型号" align="center"></el-table-column>
            <el-table-column prop="unit" label="单位" width="100" align="center"></el-table-column>
            <el-table-column prop="stockNum" label="库存数量" width="120" align="center"></el-table-column>
            <el-table-column label="盘点数量" width="150" align="center">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.inventoryNum"
                  :min="0"
                  :max="999999"
                  size="mini"
                  controls-position="right"
                  @change="calculateDiff(scope.row)"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="差异数量" width="120" align="center">
              <template slot-scope="scope">
    <span :class="{'text-success': scope.row.diffNum > 0, 'text-danger': scope.row.diffNum < 0}">
      {{ scope.row.diffNum }}
    </span>
              </template>
            </el-table-column>
            <el-table-column label="盘亏盘盈金额" width="150" align="center">
              <template slot-scope="scope">
    <span :class="{'text-success': scope.row.profitLossAmount > 0, 'text-danger': scope.row.profitLossAmount < 0}">
      {{ formatAmount(scope.row.profitLossAmount) }}
    </span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleRemoveProduct(scope.$index)"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <!-- 选择商品对话框 -->
        <el-dialog
          title="选择盘点商品"
          :visible.sync="productDialogVisible"
          width="80%"
          append-to-body>
          <div class="filter-container">
            <el-form :inline="true" size="small">
              <el-form-item label="仓库：">
                <el-select
                  v-model="productQuery.warehouseId"
                  placeholder="请选择仓库"
                  clearable
                  @change="handleWarehouseChange">
                  <el-option
                    v-for="warehouse in warehouseOptions"
                    :key="warehouse.id"
                    :label="warehouse.name"
                    :value="warehouse.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model="productQuery.keyword"
                  placeholder="请输入商品名称或编号"
                  clearable
                  @keyup.enter.native="handleProductSearch"
                />
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  @click="handleProductSearch">
                  搜索
                </el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-table
            :data="productOptions"
            border
            height="400"
            @selection-change="handleProductSelectionChange">
            <!-- 选择列 -->
            <el-table-column type="selection" width="55" align="center"></el-table-column>

            <el-table-column prop="goodsName" label="商品名称" width="180" align="center"></el-table-column>
            <el-table-column prop="goodsSn" label="商品编号" width="180" align="center"></el-table-column>
            <el-table-column prop="specification" label="规格型号" width="180" align="center"></el-table-column>
            <el-table-column prop="unit" label="单位" width="100" align="center"></el-table-column>
            <el-table-column prop="wesn" label="入库单号" width="180" align="center"></el-table-column>
            <el-table-column prop="stockNum" label="库存数量" width="120" align="center"></el-table-column>
            <el-table-column label="盘点数量" width="150" align="center">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.inventoryNum"
                  :min="0"
                  :max="999999"
                  size="mini"
                  controls-position="right"
                  @change="calculateDiff(scope.row)"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="差异数量" width="120" align="center">
              <template slot-scope="scope">
        <span :class="{'text-success': scope.row.diffNum > 0, 'text-danger': scope.row.diffNum < 0}">
          {{ scope.row.diffNum }}
        </span>
              </template>
            </el-table-column>
          </el-table>

          <div slot="footer" class="dialog-footer">
            <el-button @click="productDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmProductSelection">确定</el-button>
          </div>
        </el-dialog>


        <!-- 盘亏盘盈汇总 -->
        <el-row :gutter="20" v-if="form.productList && form.productList.length > 0" style="margin-top: 20px;">
          <el-col :span="8">
            <div class="stat-card">
              <div class="stat-title">盘盈商品种类数</div>
              <div class="stat-value text-success">{{ form.productList.filter(p => p.diffNum > 0).length }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-card">
              <div class="stat-title">盘亏商品种类数</div>
              <div class="stat-value text-danger">{{ form.productList.filter(p => p.diffNum < 0).length }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-card">
              <div class="stat-title">盘亏盘盈总金额</div>
              <div class="stat-value" :class="{'text-success': form.profitLossAmount > 0, 'text-danger': form.profitLossAmount < 0}">
                {{ formatAmount(form.profitLossAmount) }}
              </div>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listInventory,
  getInventory,
  delInventory,
  addInventory,
  updateInventory,
  auditInventory,
  getProfitLossStats
} from "@/api/system/inventory";
import { listDept } from "@/api/erpsystem/dept";
import { listWarehouse } from "@/api/system/warehouse";
import {
  getCompiler,
} from "@/api/procurementmanagement/plan";
import {listGoodsByWarehouse} from "@/api/system/transfer";

export default {
  name: "Inventory",
  data() {
    return {
      productDialogVisible: false,
      productOptions: [], // 可选商品列表
      selectedProducts: [], // 临时选中的商品
      profitLossStats: {
        totalProfitCount: 5,
        totalLossCount: 5,
        totalProfitLossAmount: 0
      },
      productQuery: {
        warehouseId: null,
        keyword: null
      },
      // 遮罩层
      loading: true,
      // 部门选项
      deptOptions: [],
      // 仓库选项
      warehouseOptions: [],
      //用户选项
      userOptions: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存盘点单表格数据
      inventoryList: [],
      //制表人
      personList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodssn: null,
        deptId: null,
        deptName: null,
        warehouseId: null,
        warehouseName: null,
        inventoryPersonId: null,
        inventoryPerson: null,
        creatorId: null,
        creator: null,
        inventoryTime: null,
        inventoryDesc: null,
        status: null,
        rejectReason: null,
        auditTime: null,
        auditPersonId: null,
        auditPersonName: null
      },
      // 表单参数
      form: {
        id: null,
        goodssn: null,
        deptId: null,
        deptName: null,
        warehouseId: null,
        warehouseName: null,
        inventoryPersonId: null,
        inventoryPerson: null,
        creatorId: null,
        creator: null,
        inventoryTime: null,
        inventoryDesc: null,
        createTime: null,
        status: null,
        rejectReason: null,
        auditTime: null,
        auditPersonId: null,
        auditPersonName: null,
        productList: [] // 商品明细列表
      },
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getDeptOptions();
    this.getWarehouseOptions();
    this.getProfitLossStats();
  },
  methods: {

    generateTempId() {
      // 使用纯数字时间戳 + 随机数
      return Date.now() + Math.floor(Math.random() * 10000);
    },
    // 打开选择商品对话框
    handleSelectProducts() {
      if (!this.form.warehouseId) {
        this.$message.warning('请先选择仓库');
        return;
      }

      this.loading = true;
      listGoodsByWarehouse(this.form.warehouseId)
        .then(response => {
          if (response.code === 200) {
            this.productOptions = response.rows.map(item => ({
              id: `${Date.now()}_${Math.floor(Math.random() * 10000)}`, // 生成临时ID
              goodsSn: item.goodsSn,      // 商品编号
              goodsName: item.goodsName,  // 商品名称
              specification: item.specification || '无规格', // 规格型号
              unit: item.unit || '个',    // 单位
              stockNum: item.num || 0,    // 库存数量
              inventoryNum: item.num || 0, // 默认盘点数量等于库存数量
              diffNum: 0,                 // 差异数量
              price: 0,                   // 默认单价为0，需要根据实际情况设置
              wesn: item.wesn,            // 入库单号
              rpm: item.rpm               // RPM信息
            }));
            this.productDialogVisible = true;
          } else {
            this.$message.error(response.msg || '获取商品列表失败');
          }
        })
        .catch(error => {
          console.error('获取商品列表失败:', error);
          this.$message.error('获取商品列表失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 加载商品选项
    loadProductOptions() {
      listGoodsByWarehouse(this.productQuery.warehouseId, this.productQuery.keyword).then(response => {
        console.log(response);
        if (response.code === 200) {
          this.productOptions = response.rows.map(item => ({
            id: item.id,
            goodssn: item.goodssn,
            goodsname: item.goodsname,
            specification: item.specification || '/',
            unit: item.unit || '个',
            stockNum: item.stockNum || 0,
            inventoryNum: item.stockNum || 0, // 默认盘点数量等于库存数量
            diffNum: 0,
            price: item.price || 0 // 商品单价
          }));
        } else {
          this.$message.error(response.msg || '获取商品列表失败');
        }
      });
    },

    // 仓库选择变化
    handleWarehouseChange() {
      this.loadProductOptions();
    },

    // 商品搜索
    handleProductSearch() {
      this.loadProductOptions();
    },

    // 处理商品选择变化
    handleProductSelectionChange(selection) {
      this.selectedProducts = selection;
    },

    // 计算差异数量
    calculateDiff(row) {
      row.diffNum = row.inventoryNum - row.stockNum;
      this.calculateTotalProfitLoss(); // 每次修改数量都重新计算总额
    },

    // 确认选择商品
    confirmProductSelection() {
      if (this.selectedProducts.length === 0) {
        this.$message.warning('请至少选择一个商品');
        return;
      }

      // 确保 productList 是数组
      if (!Array.isArray(this.form.productList)) {
        this.form.productList = [];
      }

      // 添加选中的商品，避免重复
      this.selectedProducts.forEach(product => {
        const exists = this.form.productList.some(p => p.goodsSn === product.goodsSn);
        if (!exists) {
          this.form.productList.push({
            ...product,
            diffNum: product.inventoryNum - product.stockNum
          });
        }
      });

      this.productDialogVisible = false;
      this.selectedProducts = [];
      this.calculateTotalProfitLoss(); // 计算总盘亏盘盈
    },

    // 删除商品
    handleRemoveProduct(index) {
      this.form.productList.splice(index, 1);
    },

    // 计算总盘亏盘盈
    calculateTotalProfitLoss() {
      let totalAmount = 0;
      let profitCount = 0;
      let lossCount = 0;

      if (this.form.productList && this.form.productList.length > 0) {
        this.form.productList.forEach(item => {
          // 计算每个商品的盘亏盘盈金额
          if (item.diffNum !== 0 && item.price) {
            item.profitLossAmount = Math.abs(item.diffNum) * item.price;
            // 根据差异正负设置金额正负
            item.profitLossAmount = item.diffNum > 0 ? item.profitLossAmount : -item.profitLossAmount;
            totalAmount += item.profitLossAmount;
          }

          // 统计盘盈盘亏种类数
          if (item.diffNum > 0) {
            profitCount++;
          } else if (item.diffNum < 0) {
            lossCount++;
          }
        });
      }

      // 更新表单数据
      this.form.profitLossAmount = totalAmount;
      this.form.profitCount = profitCount;
      this.form.lossCount = lossCount;
    },

    handleView(row) {
      this.reset();
      const id = row.id;
      getInventory(id).then(response => {
        this.form = response.data;
        this.form.productList = response.data.productList || [];
        this.open = true;
        this.title = "盘点单详情";
      });
    },

    // 金额格式化
    formatAmount(amount) {
      if (amount === null || amount === undefined) return '¥0.00';
      const num = parseFloat(amount);
      return num > 0 ? `+¥${num.toFixed(2)}` : `-¥${Math.abs(num).toFixed(2)}`;
    },

    // 获取盘亏盘盈统计
    getProfitLossStats() {
      getProfitLossStats().then(response => {
        if (response.code === 200) {
          this.profitLossStats = response.data;
        }
      });
    },
    // 计算盘亏盘盈金额
    calculateProfitLoss(row) {
      if (row.unitPrice && row.diffNum) {
        row.profitLossAmount = row.unitPrice * Math.abs(row.diffNum);
        if (row.diffNum > 0) {
          row.profitLossType = 'profit';
        } else if (row.diffNum < 0) {
          row.profitLossType = 'loss';
        } else {
          row.profitLossType = null;
        }
      } else {
        row.profitLossAmount = 0;
        row.profitLossType = null;
      }
    },
    // 选择商品
    // handleSelectProducts() {
    //   if (!this.form.warehouseId) {
    //     this.$message.warning('请先选择仓库');
    //     return;
    //   }
    //
    //   listGoodsByWarehouse(this.form.warehouseId).then(response => {
    //     if (response.code === 200) {
    //       this.productOptions = response.rows.map(item => ({
    //         id: item.id || 0, // 如果后端未返回 id，可以默认设为 0 或生成临时 ID
    //         productId: item.id || 0,
    //         productSn: item.goodssn,
    //         productName: item.goodsname,
    //         specification: item.spec_name,
    //         unit: item.unit || '个',
    //         stockNum: item.num,
    //         inventoryNum: item.num,
    //         diffNum: 0
    //       }));
    //       this.productDialogVisible = true;
    //     } else {
    //       this.$message.error(response.msg || '获取商品列表失败');
    //     }
    //   }).catch(error => {
    //     console.error('API 请求失败:', error);
    //     this.$message.error('请求异常，请检查网络或联系管理员');
    //   });
    // },


    // 确认选择商品
    // confirmProductSelection() {
    //   if (!this.selectedProducts || this.selectedProducts.length === 0) {
    //     this.$message.warning('请至少选择一个商品');
    //     this.selectedProducts.forEach(product => {
    //       const isExist = this.form.productList.some(
    //         p => p.productSn === product.productSn
    //       );
    //       if (!isExist) {
    //         // 初始化单价为0
    //         product.unitPrice = 0;
    //         product.profitLossAmount = 0;
    //         product.profitLossType = null;
    //         this.form.productList.push({ ...product });
    //       }
    //     });
    //     return;
    //   }
    //
    //   // 确保 this.form.productList 是数组
    //   if (!Array.isArray(this.form.productList)) {
    //     this.form.productList = [];
    //   }
    //
    //   // 遍历选中的商品，避免重复添加
    //   this.selectedProducts.forEach(product => {
    //     const isExist = this.form.productList.some(
    //       p => p.productSn === product.productSn // 根据实际字段比对
    //     );
    //     if (!isExist) {
    //       this.form.productList.push({ ...product });
    //     }
    //   });
    //
    //   this.productDialogVisible = false;
    //   this.selectedProducts = []; // 清空临时选中项
    //   console.log('selectedProducts:', this.selectedProducts);
    //   console.log('productList:', this.form.productList);
    // },

    // 在handleUpdate方法中初始化productList
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getInventory(id).then(response => {
        this.form = response.data;
        // 如果后端返回了productList，直接赋值
        if (response.data.productList) {
          this.form.productList = response.data.productList;
        } else {
          this.form.productList = [];
        }
        this.getCompiler();
        this.form.isAdd = false;
        this.open = true;
        this.title = "修改库存盘点单";
      });
    },
    /** 查询库存盘点单(es_stock_inventory)列表 */
    getList() {
      this.loading = true;
      listInventory(this.queryParams).then(response => {
        console.log(response);
        this.inventoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取部门列表 */
    getDeptOptions() {
      listDept().then(response => {
        response.data.forEach(dept => {
          dept.deptName = dept.name;
        });
        this.deptOptions = response.data;
      });
    },
    /** 获取仓库列表 */
    getWarehouseOptions() {
      listWarehouse().then(response => {
        response.rows.forEach(warehouse => {
          warehouse.warehouseName = warehouse.name;
        });
        this.warehouseOptions = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sn: null,
        deptId: null,
        deptName: null,
        warehouseId: null,
        warehouseName: null,
        inventoryPersonId: null,
        inventoryPerson: null,
        creatorId: null,
        creator: null,
        inventoryTime: null,
        inventoryDesc: null,
        createTime: null,
        status: null,
        rejectReason: null,
        auditTime: null,
        auditPersonId: null,
        auditPersonName: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.isAdd = true; // 设置新增标识
      this.form.sn = this.generateRandomSn(); // 生成随机编号（包含前缀）
      this.getCompiler(); // 获取编制人
      this.open = true;
      this.title = "添加库存盘点单";
    },
    //获取编制人
    getCompiler(){
      getCompiler().then(response => {
        this.personList = response.data;
      })
    },
    handleCreatorChange(value) {
      if (value.length > 0) {
        // 获取选中项的最后一个值作为 id
        const selectedPerson = this.personList.find(person => person.id.toString() === value[value.length - 1].toString());
        if (selectedPerson) {
          this.form.inventoryPersonId = selectedPerson.id; // 保存编制人 ID 到表单
          this.form.inventoryPerson = selectedPerson.realName; // 保存编制人名称到表单
        }
      } else {
        this.form.inventoryPersonId = null;
        this.form.inventoryPerson = null;
      }
    },
    handleCreatorChange2(value) {
      if (value.length > 0) {
        // 获取选中项的最后一个值作为 id
        const selectedPerson = this.personList.find(person => person.id.toString() === value[value.length - 1].toString());
        if (selectedPerson) {
          this.form.creatorId = selectedPerson.id; // 保存编制人 ID 到表单
          this.form.creator = selectedPerson.realName; // 保存编制人名称到表单
        }
      } else {
        this.form.creatorId = null;
        this.form.creator = null;
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.form.productList = this.form.productList.map(item => {
        // 如果是临时ID（包含_），则置为null让后端生成
        if (item.id && typeof item.id === 'string' && item.id.includes('_')) {
          return { ...item, id: null };
        }
        return item;
      });
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保所有商品都有必要的字段
          this.form.productList = this.form.productList.map(item => ({
            ...item,
            goodsName: item.goodsName || '未知商品',
            goodsSn: item.goodsSn || '',
            specification: item.specification || '无规格',
            unit: item.unit || '个',
            wesn: item.wesn || '',
            rpm: item.rpm || '无'
          }));

          // 提交前重新计算差异
          this.calculateTotalProfitLoss();

          if (this.form.id != null) {
            updateInventory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInventory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除库存盘点单(es_stock_inventory)编号为"' + ids + '"的数据项？').then(function() {
        return delInventory(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 审核按钮操作 */
    handleAudit(row) {
      const id = row.id || this.ids;
      this.$modal.confirm('是否确认审核库存盘点单(es_stock_inventory)编号为"' + id + '"的数据项？').then(() => {
        return auditInventory(id); // 调用审核接口
      }).then(() => {
        this.getList(); // 刷新列表
        this.$modal.msgSuccess("审核成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/inventory/export', {
        ...this.queryParams
      }, `inventory_${new Date().getTime()}.xlsx`)
    },
    generateRandomSn() {
      const prefix = "PD"; // 随机编号前缀
      const date = new Date();
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const randomNum = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
      return `${prefix}${year}${month}${day}${randomNum}`; // 拼接前缀和随机编号
    },
  }
};
</script>

<style scoped>
.text-success {
  color: #67C23A;
}
.text-danger {
  color: #F56C6C;
}
.text-center {
  text-align: center;
}
.mb8 {
  margin-bottom: 20px;
}
.stat-card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  text-align: center;
}
.stat-title {
  font-size: 14px;
  color: #909399;
}
.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-top: 10px;
}

.filter-container {
  margin-bottom: 15px;
}

.text-success {
  color: #67C23A;
}

.text-danger {
  color: #F56C6C;
}

/* 统一表单元素宽度 */
.uniform-width {
  width: 100% !important;
}

/* 调整表单标签样式 */
.el-form-item__label {
  width: 100px;
  text-align: right;
  padding-right: 12px;
}

/* 调整级联选择器下拉菜单宽度 */
.el-cascader-menu {
  min-width: 100%;
}

/* 调整日期选择器样式 */
.el-date-editor.el-input {
  width: 100%;
}

/* 确保表单内容区域对齐 */
.el-form-item__content {
  margin-left: 100px;
}

/* 调整文本域高度 */
.el-textarea__inner {
  min-height: 80px;
  resize: vertical;
}

/* 下拉菜单最小宽度 */
.el-select-dropdown {
  min-width: 100% !important;
}

/* 操作按钮样式 */
.dialog-footer {
  text-align: right;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  margin-top: 20px;
}
</style>
